package com.boarsoft.boar.deploy.file;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;

import com.boarsoft.agent.AgentService;
import com.boarsoft.boar.BaseConfig;
import com.boarsoft.boar.deploy.bean.BuildInstParam;
import com.boarsoft.common.Util;
import com.boarsoft.flow.core.bean.ProcessHandler;
import com.boarsoft.rpc.core.RpcContext;

/**
 * 此Handler会调用位于打包服务器的agentC，再由agentC调用位于目标服务器的agentX<br>
 * agentC到agentX是通过方法调用传参（二进制流）的方式来传输文件。<br>
 * 
 * @author Mac_J
 *
 */
public class TransferFilePH implements ProcessHandler {
	private static Logger log = LoggerFactory.getLogger(TransferFilePH.class);

	@Autowired
	@Lazy
	@Qualifier("agentC")
	private AgentService agentC;

	@Override
	public Object process(String entry, Object data, Throwable throwable) throws Throwable {
		BuildInstParam p = (BuildInstParam) data;
		String ps = p.getPackServer();
		if (Util.strIsEmpty(ps)) {
			throw new IllegalStateException("Pack server of build item is empty");
		}
		// 目标服务器AgentX地址（IP:PORT）
		String axa = new StringBuilder().append(p.getIp()).append(":")//
				.append(BaseConfig.AGENTX_PORT).toString();
		// 打包（源）目录（当前服务器）
		String pp = p.getPackPath();
		// 远程部署（目标）目录
		String to = new File(pp).getName();
		// data为需要传输到指定目标地址的部署项列表
		log.info("Ask agentC {} copy file {} to {}:{}", ps, pp, p.getIp(), to);
		// 调用agentC来传输文件
		RpcContext.specify2(ps);
		try {
			agentC.copy2(pp, to, axa);
		} finally {
			RpcContext.specify2(null);
		}
		return data;
	}
}